﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace Usermanagment.DBConnection
{
   public class DBConnect
    {
       private MySqlConnection connection;
       private string server;
       private string username;
       private string password;
       private string database;
       private string conString;
       private Boolean init = false ,isConnected = false;
	   private String message;

       public string Sserver
       {
           get { return server; }
           set { server = value; init = false; }
       }

       public string User
       {
           get { return username; }
           set { username = value; init = false; }
       }

       public string Password
       {
           get { return password; }
           set { password = value; init = false; }
       }

       public string Database
       {
           get { return database; }
           set { database = value; init = false; }
        }

       private void initialize()
       {
           conString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + username + ";"
               + "PASSWORD=" + password + ";";
           init = true;
       }

        public Boolean OpenConnection()
       {

            try
            {
                if (!init)
                    initialize();
                connection = new MySqlConnection(conString);
                connection.Open();
                isConnected = true;
				message = "Connected!";
                return true;
                
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        message = "Cant Connect to server";
                        break;
                    case 1045:
                        message = "Bad username/Password";
                        break;
					default:
						message = ex.Message;
						break;
                }
                return false;
            }

       }

        public Boolean closeConnection()
        {

            try
            {
                if (isConnected)
                {
                    connection.Close();
                    isConnected = false;
					message = "Disconnected";
                }
                return true;
            }
            catch (System.Exception ex)
            {
               message = (ex.Message);
                return false;
            }
        }
        public Boolean Connected()
        {
            return isConnected;

        }

        public MySqlConnection getCon()
        {
            return connection;
        }

		public String getMsg()
		{
			return message;
		}

    }
}
